import * as THREE from 'three';
//导入轨道控制器
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';

import './style.css';

// 首先创建场景
const scene = new THREE.Scene();

// 创建相机（角度，宽高比，可视距离区间）设置视锥体尺寸
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);

// 设置相机xyz的位置
camera.position.set(0, 0, 10);

// 给场景添加摄像机
scene.add(camera);

// 建一个立方缓冲几何体，立方体的方法是new THREE.BoxGeometry(x,y,z);
const geometry = new THREE.SphereGeometry(1, 32, 32);

// 创建几何体的材质
const material = new THREE.MeshLambertMaterial({
  color: 0xff6600, //设置材质颜色
});

const material2 = new THREE.MeshLambertMaterial({
  color: 0xffffff, //设置材质颜色
});
const material3 = new THREE.MeshLambertMaterial({
  color: 0xffffff, //设置材质颜色
});
// 物体需要几何体和材质来创建，把新建的立方体和材质，创建网格的风格创建出来
const cube = new THREE.Mesh(geometry, material);
const cube2 = new THREE.Mesh(geometry, material2);
const cube3 = new THREE.Mesh(geometry, material3);

// 把网格添加到场景中
scene.add(cube, cube2, cube3);
cube2.position.set(-4, 0, 0);
cube3.position.set(4, 0, 0);

// 创建射线
const raycaster = new THREE.Raycaster();
// 创建鼠标向量，记录鼠标点击的位置
const mouse = new THREE.Vector2();
window.addEventListener('click', (e) => {
  mouse.x = (e.clientX / window.innerWidth) * 2 - 1;
  mouse.y = -(e.clientY / window.innerHeight) * 2 + 1;
  // 通过鼠标点击的位置，和当前相机的矩阵计算出raycaster
  raycaster.setFromCamera(mouse, camera);
  // 获取raycaster直线和所有模型相交的数组
  const intersects = raycaster.intersectObjects([cube, cube2, cube3]);
  console.log('intersects', intersects);
  // 证明点击到了物体
  if (intersects.length > 0) {
    if (intersects[0].object.isSelect) {
      intersects[0].object.material.color.setHex(intersects[0].object.oldColor);
      intersects[0].object.isSelect = false;
      return;
    }
    intersects[0].object.isSelect = true;
    intersects[0].object.oldColor =
      intersects[0].object.material.color.getHex();
    intersects[0].object.material.color.setHex(0xff0000);
  }
});
// 初始化渲染器 antialias抗锯齿
const renderer = new THREE.WebGLRenderer({ antialias: true });
// 指定渲染器的尺寸大小
renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);

renderer.render(scene, camera);

// 创建轨道控制器，并让轨道控制器调用摄像机，和渲染器的dom元素
const controls = new OrbitControls(camera, renderer.domElement);

// 添加坐标轴辅助器（坐标轴的长度）
// axes:轴 helper:辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper); // 把坐标轴添加到场景中

// 添加环境光
const ambientLight = new THREE.AmbientLight(0xffffff);
ambientLight.position.set(0, 400, 0); //点光源放在x轴上

ambientLight.intensity = 2.0; //光照强度
// ambientLight.intensity = 50000.0; //光照强度

scene.add(ambientLight);

// const light = new THREE.DirectionalLight(0xffffff, 0.5);
// light.position.set(15, 20, 0);
// scene.add(light);

// 渲染函数
function animate() {
  controls.update();

  // 渲染场景
  renderer.render(scene, camera);
  // 渲染下一帧的时候就会调用render函数
  requestAnimationFrame(animate);
}

animate();
